using DataFrames
using QuadGK
using Distributions
using CSV
using LinearAlgebra
using JLD
using Interpolations

clearconsole()

#-------------------------------------------------------------
# include Functions
#-------------------------------------------------------------
#cd("$(pwd())/Dropbox/Heterogeneity/Software/KS_Simulation/")
readDir = "$(pwd())/Functions/"
include(readDir *"vech.jl");
include(readDir *"logSpline_Procedures.jl");
include(readDir *"VAR_Procedures.jl");
include(readDir *"Loaddata.jl");

#-------------------------------------------------------------
# choose specification files
#-------------------------------------------------------------
nDataSel  = '1'
nfVARSpec = "3"
nModSpec  = "3"
nMCMCSpec = "1"
modName   = "SS"

specDir   = "$(pwd())/SpecFiles/"
include(specDir * "/fVARspec" * nfVARSpec * ".jl")
include(specDir * "/" * modName * "spec" * nModSpec * ".jl")
include(specDir * "/" * modName * "MCMCspec" * nMCMCSpec * ".jl")

#-------------------------------------------------------------
# load aggregate data to obtain unemployment rate
#-------------------------------------------------------------
agg_data = loadaggdata(1,Tend)
n_agg    = size(agg_data)[2]


#-------------------------------------------------------------
# Generate Lambda matrix and vector of means to convert a factors
#-------------------------------------------------------------
sNameLoadDir = "fVAR" * nfVARSpec
loaddir  = "$(pwd())/results/Para" *nDataSel *"/" * sNameLoadDir *"/";
PhatDensCoef_factor, MDD_GoF, VinvLam_all, PhatDensCoef_lambda, PhatDensCoef_mean = loaddensdata(1,Tend,K,nfVARSpec)

# later, undo the transformation using inverse hyperbolic sine transform with theta
theta = 1.0

#-------------------------------------------------------------
# Load state's posterior mean
#-------------------------------------------------------------

sName    = "fVAR" * nfVARSpec * "_" * modName * nModSpec * "_" * "MCMC" * nMCMCSpec;
loadDir  = "$(pwd())/results/Para" *nDataSel * "/" * sName *"/";

PhatDensCoef_factor_smoothed = load(loadDir * sName * "_StateMeans.jld", "alphapmean_smoothed")
T = size(PhatDensCoef_factor_smoothed)[1]
K = size(PhatDensCoef_factor_smoothed)[2]

PhatDensCoef_smoothed = zeros(T,K)

for tt = 1:T

    print("Smoothed States for Period = $tt \n")
    PhatDensCoef_smoothed[tt,:] = coefRecover(PhatDensCoef_factor_smoothed[tt,:]',PhatDensCoef_lambda, PhatDensCoef_mean)

end

savedir  = "$(pwd())/results/Para" *nDataSel *"/" * sName *"/";
CSV.write(savedir * sName * "_PhatDensCoef_Smoothed.csv", DataFrame(PhatDensCoef_smoothed,:auto));
CSV.write(savedir * sName * "_PhatDensCoef_factor_Smoothed.csv", DataFrame(PhatDensCoef_factor_smoothed,:auto));
